package de.nordakademie.wpk.share.core.data;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import de.nordakademie.wpk.share.core.data.treeitem.TreeItem;

/**
 * Represents a depot or an index on the server
 * 
 * @author Christian Baumhof
 */
public class Depot extends TreeItem implements Serializable {

	private static final long serialVersionUID = 1397650755554973269L;

	private Integer id;
	private String name = "";
	private String description = "";
	private List<Share> shares = new ArrayList<Share>();
	private TreeItem.Type type;

	public Depot(Type type) {
		this.type = type;
	}

	public Depot(Integer id, String name, String description, Type type) {
		this.id = id;
		this.name = name;
		this.description = description;
		this.type = type;
	}

	public BigDecimal getTotalValue() {
		BigDecimal totalValue = new BigDecimal(0);
		for (Share share : shares) {
			totalValue = totalValue.add(share.getTotalValue());
		}
		return totalValue;
	}

	/**
	 * Returns the average value for the last 30 days
	 * 
	 * @return BigDecimal
	 */
	public BigDecimal getAverageValue() {
		BigDecimal avgValue = new BigDecimal(0);
		for (Share share : shares) {
			BigDecimal quantity = new BigDecimal(share.getQuantity());
			avgValue = avgValue.add(share.getAverageQuote().multiply(quantity));
		}
		return avgValue;
	}

	public String getPercentageChange() {
		BigDecimal closingValue = new BigDecimal(1);
		for (Share share : shares) {
			BigDecimal shareClosingValue = share.getPreviousClose().multiply(
					new BigDecimal(share.getQuantity()));
			closingValue = closingValue.add(shareClosingValue);
		}
		BigDecimal currentValue = getTotalValue();

		BigDecimal change = currentValue.divide(closingValue, 2);
		change = change.subtract(new BigDecimal(1));
		change = change.multiply(new BigDecimal(100));

		if (change.compareTo(new BigDecimal(0)) > 0) {
			return "+" + change + "%";
		} else {
			return change + "%";
		}

	}

	public String getPercentageChangeMonth() {
		return "";
	}

	public Boolean isShareInDepot(String symbol) {
		for (Share share : shares) {
			if (share.getSymbol().equals(symbol)) {
				return true;
			}
		}
		return false;
	}

	public void addShare(Share share) {
		shares.add(share);
	}

	public List<Share> getShares() {
		return shares;
	}

	public void setShares(List<Share> shares) {
		this.shares = shares;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Override
	public Type getType() {
		return type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}
